package com.ruoyi.system.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.tea.TeaModel;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.WaterMark;
import com.ruoyi.system.domain.FyPeople;
import com.ruoyi.system.domain.FyProject;
import com.ruoyi.system.domain.vo.DataTemplateVo;
import com.ruoyi.system.domain.vo.DeleteIdVo;
import com.ruoyi.system.domain.vo.ProjectTemplateVo;
import com.ruoyi.system.service.IFyPeopleService;
import com.ruoyi.system.service.IFyProjectService;
import com.ruoyi.system.util.WaterMark2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.FyData;
import com.ruoyi.system.service.IFyDataService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 资料Controller
 *
 * @author ruoyi
 * @date 2025-06-05
 */
@RestController
@RequestMapping("/system/data")
public class FyDataController extends BaseController
{
    @Autowired
    private IFyDataService fyDataService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    RuoYiConfig ruoYiConfig;
    @Autowired
    private IFyProjectService fyProjectService;
    @Autowired
    private IFyPeopleService fyPeopleService;
    /**
     * 查询资料列表
     */
//    @PreAuthorize("@ss.hasPermi('system:data:list')")
    @GetMapping("/list")
    public TableDataInfo list(FyData fyData)
    {
        startPage();
        List<FyData> list = fyDataService.selectFyDataList(fyData);
        return getDataTable(list);
    }
    @GetMapping("/list2")
    public TableDataInfo list2(FyData fyData)
    {

        fyData.setDataType(1l);
        List<FyData> list = fyDataService.selectFyDataList(fyData);
        for (FyData fd:list){
            fd.setDataUrl(fd.getDataUrl()+ruoYiConfig.getOssshuiyin());
            fyDataService.updateFyData(fd);
        }
        return getDataTable(list);
    }

    /**
     * 导出资料列表
     */
    @PreAuthorize("@ss.hasPermi('system:data:export')")
    @Log(title = "资料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FyData fyData)
    {
        List<FyData> list = fyDataService.selectFyDataList(fyData);
        ExcelUtil<FyData> util = new ExcelUtil<FyData>(FyData.class);
        util.exportExcel(response, list, "资料数据");
    }

    /**
     * 获取资料详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:data:query')")
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfo(Long dataId)
    {
        return success(fyDataService.selectFyDataByDataId(dataId));
    }

    /**
     * 新增资料
     */
//    @PreAuthorize("@ss.hasPermi('system:data:add')")
    @Log(title = "资料", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody FyData fyData)
    {
        redisCache.deleteObject("home:count");
        if (fyData.getPeopleId()!=null){
            FyPeople people=fyPeopleService.selectFyPeopleByPeopleId(fyData.getPeopleId());
            fyData.setPeopleName(people.getPeopleName());
        }
        if (fyData.getProjectId()!=null){
            FyProject project=fyProjectService.selectFyProjectByProjectId(fyData.getProjectId());
            fyData.setProjectName(project.getProjectName());
        }
        if (fyData.getDataFormat()!=null){
            fyData.setDataFormat(fyData.getDataFormat().replaceAll("1","jpg").replaceAll("4","PDF")
                    .replaceAll("2","mp4").replaceAll("3","mp3")

            );
        }
        if (fyData.getDataType()==1){
            fyData.setDataUrl(fyData.getDataUrl()+ruoYiConfig.getOssshuiyin());
        }
        return toAjax(fyDataService.insertFyData(fyData));
    }

    /**
     * 修改资料
     */
//    @PreAuthorize("@ss.hasPermi('system:data:edit')")
    @Log(title = "资料", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody FyData fyData)
    {
        if (fyData.getPeopleId()!=null){
            FyPeople people=fyPeopleService.selectFyPeopleByPeopleId(fyData.getPeopleId());
            fyData.setPeopleName(people.getPeopleName());
        }
        if (fyData.getProjectId()!=null){
            FyProject project=fyProjectService.selectFyProjectByProjectId(fyData.getProjectId());
            fyData.setProjectName(project.getProjectName());
        }
        if (fyData.getDataFormat()!=null){
            fyData.setDataFormat(fyData.getDataFormat().replaceAll("1","jpg").replaceAll("4","PDF")
                    .replaceAll("2","mp4").replaceAll("3","mp3")

            );
        }
        return toAjax(fyDataService.updateFyData(fyData));
    }


    /**
     * 删除资料
     */
//    @PreAuthorize("@ss.hasPermi('system:data:remove')")
    @Log(title = "资料", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteIdVo projectIds)
    {
        redisCache.deleteObject("home:count");
        return toAjax(fyDataService.deleteFyDataByDataIds(projectIds.getDataIds()));
    }

    /**
     * 下载资料模版
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/template")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    public void template(HttpServletResponse response) throws UnsupportedEncodingException {
        List<DataTemplateVo> list = new ArrayList<>();
        DataTemplateVo dataTemplateVo=new DataTemplateVo();
        dataTemplateVo.setDataName("资源名称");
        dataTemplateVo.setProjectName("项目名称（资源所属项目名称）");
        dataTemplateVo.setPeopleCode("人工编码（对应图片音频文件名称，例：文件名称为：传统工艺.jpg，人工编码填写:传统工艺.jpg）");
        dataTemplateVo.setDataType("图片/影音/文件");
        dataTemplateVo.setDataFormat("jpg/mp3/mp4/PDF");
        dataTemplateVo.setJibie("浏览级");
        dataTemplateVo.setJigou("朝阳");
        dataTemplateVo.setZhuluPeople("张三");
        dataTemplateVo.setZhuluTime("2011年12月1日");
        list.add(dataTemplateVo);
        ExcelUtil<DataTemplateVo> util = new ExcelUtil<DataTemplateVo>(DataTemplateVo.class);
        String fileName = URLEncoder.encode("资源上传模版" + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        util.exportExcel(response, list, "资源上传模版");
    }
    @PostMapping("/importData")
    @Transactional
    public AjaxResult importData(MultipartFile excelfile,MultipartFile[] files) throws Exception
    {
        ExcelUtil<DataTemplateVo> util = new ExcelUtil<DataTemplateVo>(DataTemplateVo.class);
        List<DataTemplateVo> voList = util.importExcel(excelfile.getInputStream());
        for(DataTemplateVo l:voList){
            FyData fyData=new FyData();
            BeanUtils.copyBeanProp(fyData,l);
            fyData.setDataType(Long.valueOf(
                    l.getDataType().replaceAll("图片","1")
                            .replaceAll("影音","2").replaceAll("文件","3")));
            String type = l.getDataFormat();
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type  + "/"+ DateUtils.YYYYMMDD() +"/" +  l.getPeopleCode() ;

            fyData.setDataUrl(url);
            FyProject project=new FyProject();
            project.setProjectName(l.getProjectName());
            List<FyProject> list = fyProjectService.selectFyProjectList2(project);

            fyData.setProjectId(list.get(0).getProjectId());
            fyDataService.insertFyData(fyData);
        }
        for (MultipartFile file:files) {

            OSS ossClient = new OSSClientBuilder().build(ruoYiConfig.getEndpoint(), ruoYiConfig.getAccessKeyId(), ruoYiConfig.getAccessKeySecret());
            ObjectMetadata omd = new ObjectMetadata();
            String status = "";
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String imgName = file.getOriginalFilename();
            if (ossClient.doesBucketExist(ruoYiConfig.getBucketName())) {
                System.out.println("您已经创建Bucket：" + ruoYiConfig.getBucketName() + "。");
            } else {
                System.out.println("您的Bucket不存在，创建Bucket：" + ruoYiConfig.getBucketName() + "。");

                ossClient.createBucket(ruoYiConfig.getBucketName());
            }
            if (type == "mp4" || type.equals("mp4")) {
                omd.setContentType("video/mp4");
                status = "0";
            }
            if (type == "mp3" || type.equals("mp3")) {
                omd.setContentType("audio/mpeg");
                status = "0";
            }
            if (type == "pdf" || type.equals("pdf") || type.equals("PDF") || type == "PDF") {
                omd.setContentType("application/pdf");
                status = "0";
            }
            if (type == "jpg" || type.equals("jpg")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (type == "png" || type.equals("png")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (StringUtils.isEmpty(status)) {
                return AjaxResult.error("请输入上传正确格式的文件--> .jpg/.png/mp4/mp3/.pdf");
            }
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            ossClient.putObject(ruoYiConfig.getBucketName(), type + "/"+ DateUtils.YYYYMMDD() +"/" + imgName, file.getInputStream(), omd);
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type  + "/"+ DateUtils.YYYYMMDD() +"/" +  imgName + ruoYiConfig.getOssshuiyin();
            ossClient.setObjectAcl(ruoYiConfig.getBucketName(), type  + "/"+ DateUtils.YYYYMMDD() +"/" + imgName, CannedAccessControlList.PublicRead);
            ossClient.shutdown();
            ossClient.shutdown();
        }

        return AjaxResult.success();
    }
    @GetMapping("/jiashuiyin")
    public AjaxResult jiashuiyin() throws Exception {
        FyData fyData=new FyData();
        fyData.setDataFormat("mp4");
        List<FyData> list = fyDataService.selectFyDataList(fyData);
        for (FyData fd:list){

            submitImageWaterMarkJobs(fd.getPeopleCode());
        }

        return AjaxResult.success();
    }

    /**
     * 提交图片水印转码作业
     * @return
     * @throws Exception
     */
    public void   submitImageWaterMarkJobs(String peopleCode) throws Exception {
        com.aliyun.mts20140618.Client client = WaterMark2.createClient();
        //构建水印输出配置
        JSONArray waterMarks = new JSONArray();  //水印数组大小上限为4，即同一路输出最多支持4个水印

        //图片水印
        JSONObject imageWaterMarks = new JSONObject();
        imageWaterMarks.put("WaterMarkTemplateId","0ea162db23444cddb99bd6d0e897cb21");
        imageWaterMarks.put("Type","Image");

        //水印图片路径
        JSONObject logoFile = new JSONObject();
        logoFile.put("Bucket","xunli-chaoyangfy");
        logoFile.put("Location","oss-cn-beijing");
        //图片Object可按需替换为png静态图片、png动图(文件后扩展名需为apng)、mov、gif文件，当素材为非静态图片时，文件扩展名需小写
        logoFile.put("Object", URLEncoder.encode("sy.png", "utf-8"));

        imageWaterMarks.put("InputFile",logoFile.toJSONString());
        waterMarks.add(imageWaterMarks);
        com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
                //作业输入
                .setInput("{\"Bucket\":\"xunli-chaoyangfy\",\"Location\":\"oss-cn-beijing\",\"Object\":\"chaoyangfy20250711%2F影音%2F"+peopleCode+".mp4\"}")
                //作业输出配置
                .setOutputs("[{\"OutputObject\":\"chaoyangfy20250711%2Fmp4%2F"+peopleCode+".mp4\",\"TemplateId\":\"53d65b52587d4343a43851f4101e7e25\",\"WaterMarks\":" + waterMarks.toJSONString() + "}]")

                //输出文件所在的OSS Bucket
                .setOutputBucket("xunli-chaoyangfy")
                //输出文件所在的 OSS Bucket 的地域（OSS Region）
                .setOutputLocation("oss-cn-beijing")
                //管道ID
                .setPipelineId("cb90ed0234c54a2a95fdb4b95def1256");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        com.aliyun.mts20140618.models.SubmitJobsResponse resp = client.submitJobsWithOptions(submitJobsRequest, runtime);
        com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));

    }

}
